#include "httpmgr.h"

HttpMgr::~HttpMgr()
{

}

HttpMgr::HttpMgr()
{
    connect(this,&HttpMgr::sig_http_finish,this,&HttpMgr::slot_http_finish);

}

void HttpMgr::PostHttpReq(QUrl url, QJsonObject json, ReqId req_id, Modules mod)
{
    QByteArray data = QJsonDocument(json).toJson();
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,QByteArray::number(data.length()));
    // 生成一个智能指针
    auto self = shared_from_this();
    QNetworkReply* reply = _manager.post(request,data);

    // 处理返回值 reply
    QObject::connect(reply,&QNetworkReply::finished,[/*this*/self,reply,req_id,mod](){
        // 错误情况
        if(reply->error() != QNetworkReply::NoError){
            qDebug() << reply->errorString();

            // 发送信号通知完成,传给其他模块
            emit self->sig_http_finish(req_id,"",ErrorCodes::ERR_NETWORK,mod);
            // 让qt释放
            reply->deleteLater();
            return;
        }

        // 无错误
        QString res = reply->readAll();
        // 信号传参数是传引用吗?不然效率? TODO
        emit self->sig_http_finish(req_id,res,ErrorCodes::SUCCESS,mod);
        reply->deleteLater();
        return;
    });
}

void HttpMgr::slot_http_finish(ReqId id, QString res, ErrorCodes err, Modules mod)
{
    if(mod == Modules::REGISTERMOD){
        // 发送信号http响应结束
        emit sig_reg_mod_finish(id,res,err);
    }

    if(mod == Modules::REGISTERMOD){
        // 发送信号通知指定模块http响应结束
        emit sig_reset_mod_finish(id,res,err);
    }

    if(mod == Modules::LOGINMOD){
        emit sig_login_mod_finish(id,res,err);
    }
}
